package com.banmao.mall.service.client.impl;

import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.client.coupon.CouponListBO;
import com.banmao.mall.model.pojo.*;
import com.banmao.mall.model.vo.admin.goods.GoodsVO;
import com.banmao.mall.model.vo.client.index.CouponVO;
import com.banmao.mall.service.client.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public List<CouponVO> selectCouponsWithPageAndSize(Integer page, Integer size) {
        //将过期的优惠券状态更改
        couponMapper.alterOutDateCouponStatus();
        List<CouponVO> voList = couponMapper.selectCouponsWithPageAndSize(page, size);
        return voList;
    }

    @Override
    public Integer receiveService(Integer userId, Integer couponId) {

        /**
         * 1.删除的或者发放完                  state=0
         * 2.如果优惠券不为空，判断能否获取     state=1表示添加成功
         * 3.state=2 表示领取达到上限
         */
        Integer state = -1;
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        //我没想到，界面上有的优惠券数据库里竟然找不到，找不到就说它送完了
        if (coupon == null) {
            state = 0;
            return state;
        }

        List<CouponUser> list = couponMapper.selectCouponUserByUserIdAndCouponId(userId, couponId);

        CouponUser couponUser = new CouponUser();
        couponUser.setUserId(userId);
        couponUser.setCouponId(couponId);
        couponUser.setStatus((short) 0);
        couponUser.setStartTime(new Date(System.currentTimeMillis()));

        /**
         * 在这里判断优惠券的有效时间限制
         * 0,是基于天数
         * 1.是基于绝对日期
         */
        if(coupon.getTimeType()==0){
            couponUser.setEndTime(new Date(System.currentTimeMillis()+(1000*60*60*24*coupon.getDays())));
        }
        else if(coupon.getTimeType()==1){
            if (coupon.getEndTime() != null) {
                couponUser.setEndTime(coupon.getEndTime());
            }
        }
        couponUser.setAddTime(new Date(System.currentTimeMillis()));
        couponUser.setUpdateTime(new Date(System.currentTimeMillis()));
        couponUser.setDeleted(false);

        //代表删除或者领完
        if (coupon.getDeleted()) {
            state = 0;
            //若果限制领券的次数
        } else if (coupon.getLimit() > 0) {
            if (list == null || list.size() < coupon.getLimit()) {
                couponUserMapper.insert(couponUser);
                if (coupon.getTotal() > 0) {//证明优惠券不是无限次的
                    if (coupon.getTotal() == 1) {
                        couponMapper.deleteByPrimaryKey(couponId);
                    } else {
                        couponMapper.updateTotalById(couponId, (coupon.getTotal() - 1));
                    }
                }
                state = 1;
            } else if (list.size() == coupon.getLimit()) {
                state = 2;
            }
        } else {
            couponUserMapper.insert(couponUser);
            if (coupon.getTotal() > 0) {//证明优惠券不是无限次的
                if (coupon.getTotal() == 1) {
                    couponMapper.deleteByPrimaryKey(couponId);
                } else {
                    couponMapper.updateTotalById(couponId, (coupon.getTotal() - 1));
                }
            }
            state = 1;
        }
        return state;
    }

    @Override
    public List<CouponVO> getUserCouponByStatus(Integer userId, CouponListBO couponListBO) {
        List<CouponUser> list = couponUserMapper.selectByUserIdAndStatus(userId,
                couponListBO.getStatus(), couponListBO.getSize(), couponListBO.getPage());
        List<CouponVO> voList = new ArrayList<>();
        //客户在查询自己的优惠券时，同样需要对优惠券状态先更改
        couponMapper.alterOutDateCouponStatus();
        for (CouponUser couponUser : list) {
            CouponVO couponVO = couponMapper.selectVOByPrimaryKey(couponUser.getCouponId());
            couponVO.setStartTime(couponUser.getStartTime());
            couponVO.setEndTime(couponUser.getEndTime());
            voList.add(couponVO);
        }
        return voList;
    }

    @Override
    public Integer exchangeService(Integer userId, String code) {

        /**
         * 0.券码不正确
         * 1.优惠券已经发放完
         * 2.不能再领
         *   （2）数量达到上限
         * 3.可以正常添加
         * 4.对优惠的数量处理
         */

        Integer state = -1;
        Coupon coupon = couponMapper.selectByCode(code);

        if (coupon == null) {
            state = 0;
        } else if (coupon.getDeleted()) {
            state = 1;
        } else {
            List<CouponUser> list = couponMapper.selectCouponUserByUserIdAndCouponId(userId, coupon.getId());

            if (coupon.getLimit() == 0 || list == null || list.size() < coupon.getLimit()) {
                CouponUser couponUser = new CouponUser();
                couponUser.setUserId(userId);
                couponUser.setCouponId(coupon.getId());
                couponUser.setStatus((short) 0);
                couponUser.setStartTime(coupon.getStartTime());
                couponUser.setEndTime(coupon.getEndTime());
                couponUser.setAddTime(new Date(System.currentTimeMillis()));
                couponUser.setUpdateTime(new Date(System.currentTimeMillis()));
                couponUser.setDeleted(false);

                couponUserMapper.insert(couponUser);

                if (coupon.getTotal() > 0) {//证明优惠券不是无限次的,需要库存善后处理
                    if (coupon.getTotal() == 1) {
                        couponMapper.deleteByPrimaryKey(coupon.getId());
                    } else {
                        couponMapper.updateTotalById(coupon.getId(), (coupon.getTotal() - 1));
                    }
                }
                state = 3;
            } else if (list.size() == coupon.getLimit()) {
                state = 2;
            }
        }
        return state;
    }

    @Override
    public List<CouponVO> CouponSelectlist(Integer userId, Integer cartId, Integer grouponRulesId) {
        /**
         * 1.先获取用户所拥有的有效的优惠券
         * 2.再通过购物车获取商品的ID，查询是否有这些商品的
         */
        //通过这两句可以获取商品的id
        List<Cart> carts = cartMapper.selectByUserId(userId);

        //收集商品id号
        List<Integer> goodIdList = new ArrayList<>();
        for (Cart cart : carts) {
            goodIdList.add(cart.getGoodsId());
        }
        //可以获取商品的类型
        List<Integer> goodsTypeList = new ArrayList<>();
        for (Cart cart : carts) {
            GoodsVO goodsVO = goodsMapper.selectByGoodsID(cart.getGoodsId());
            goodsTypeList.add(goodsVO.getCategoryId());
        }

//        GoodsVO goodsVO1 = goodsMapper.selectByGoodsID(grouponRules.getGoodsId());


        List<CouponUser> list = couponUserMapper.selectAllUserEffectiveCoupon(userId);


        List<Coupon> coupons = new ArrayList<Coupon>();
        for (CouponUser couponUser : list) {
            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
            if (coupon.getGoodsType() == 0) {
                coupon.setStartTime(couponUser.getStartTime());
                coupon.setEndTime(couponUser.getEndTime());
                coupons.add(coupon);
            } else if (coupon.getGoodsType() == 1) {

                String[] goodsValue = coupon.getGoodsValue();
                for (String s : goodsValue) {
                    for (int i = 0; i < goodsTypeList.size(); i++) {
                        if (s.equals(goodsTypeList.indexOf(i) + "")) {
                            coupon.setStartTime(couponUser.getStartTime());
                            coupon.setEndTime(couponUser.getEndTime());
                            coupons.add(coupon);
                        }
                    }
                }
            } else {
                String[] goodsValue = coupon.getGoodsValue();
                for (String s : goodsValue) {
                    for (int i = 0; i < goodIdList.size(); i++) {
                        if (s.equals(goodIdList.indexOf(i) + "")) {
                            coupon.setStartTime(couponUser.getStartTime());
                            coupon.setEndTime(couponUser.getEndTime());
                            coupons.add(coupon);
                        }
                    }
                }
            }
        }


        ArrayList<CouponVO> couponVOS = new ArrayList<>();
        for (Coupon coupon : coupons) {
            CouponVO couponVO = new CouponVO();
            couponVO.setId(coupon.getId());
            couponVO.setName(coupon.getName());
            couponVO.setDesc(coupon.getDesc());
            couponVO.setTag(coupon.getTag());
            couponVO.setDiscount(coupon.getDiscount());
            couponVO.setMin(coupon.getMin());
            couponVO.setDays((int) coupon.getDays());
            couponVO.setStartTime(coupon.getStartTime());
            couponVO.setEndTime(coupon.getEndTime());

            couponVOS.add(couponVO);
        }

        return couponVOS;

    }
}
